package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 利用信号量来实现打印机串行化
 * Created by gavin on 15-9-1.
 */
public class SemaphoreTest {
    public static void main(String[] args)
    {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        PrintQueue prentQueue = new PrintQueue();
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(new PrintJob(prentQueue));
        }

    }
}

class PrintJob implements Runnable{
    private PrintQueue printQueue;

    public PrintJob(PrintQueue printQueue) {
        this.printQueue = printQueue;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName()+"  prepare print");
        printQueue.printJob(new Object());
        System.out.println(Thread.currentThread().getName() + "  it is ok");
    }
}


class PrintQueue{
    private final Semaphore semaphore;

    public PrintQueue() {
        semaphore = new Semaphore(1);
    }

    public void printJob(Object document)
    {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+"  start print");
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName()+"  finish print");
        }catch (InterruptedException e)
        {
            e.printStackTrace();
        }finally {
            semaphore.release();
        }
    }
}
